package manager

import (
	"fmt"
	"github.com/tianjigames/fairy/model"
	"github.com/topfreegames/pitaya/logger"
	"sync"
)

var (
	GameServerPlayerManager *gameServerPlayerManager
	gameServerPlayerManagerOnce sync.Once
)

/**
游戏玩家管理器
 */
type gameServerPlayerManager struct {
	BaseManager
	allPlayerOnGameServerMap  map[string]*model.PlayerInfo //游戏服务器上所有玩家列表
	onlineIdMap map[int]int64 //在线玩家列表
	onlineMap map[int64]*model.PlayerInfo
}

func NewGameServerPlayerManager() *gameServerPlayerManager {
	gameServerPlayerManagerOnce.Do(func() {
		GameServerPlayerManager = &gameServerPlayerManager{
			allPlayerOnGameServerMap: map[string]*model.PlayerInfo{},
			onlineIdMap: map[int]int64{},
			onlineMap: map[int64]*model.PlayerInfo{},
		}
	})
	return GameServerPlayerManager
}

/**
生成玩家唯一key
*/
func (p *gameServerPlayerManager) generateAllPlayerOnGameServerMapKey(accountId int64,appId string) string {
	return fmt.Sprintf("%d%s",accountId,appId)
}

/**
获取一个在游戏服务器上玩家信息
*/
func (p *gameServerPlayerManager) GetPlayerInfoByAccount(accountId int64,appId string) *model.PlayerInfo {
	return p.allPlayerOnGameServerMap[p.generateAllPlayerOnGameServerMapKey(accountId,appId)]
}

/**
添加一个玩家信息到游戏服务器
*/
func (p *gameServerPlayerManager) AddPlayerInfo(accountId int64,appId string,info *model.PlayerInfo)  {
	logger.Log.Infof("AddPlayerInfo:accountId=%d",accountId)
	p.allPlayerOnGameServerMap[p.generateAllPlayerOnGameServerMapKey(accountId,appId)] = info
}

/**
设置某个玩家在线
 */
func (p *gameServerPlayerManager) SetPlayerOnline(accountId int64,appId string) *model.PlayerInfo {
	info,ok := p.allPlayerOnGameServerMap[p.generateAllPlayerOnGameServerMapKey(accountId,appId)]
	if ok {
		info.IsOnline = true
		p.onlineIdMap[info.PlayerId] = info.PlayerGuid
		p.onlineMap[info.PlayerGuid] = info
	}
	return info
}